<?php

use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
use \Workerman\Lib\Timer;


class Events
{
    // 当有客户端连接时，将client_id返回，让mvc框架判断当前uid并执行绑定
    public static function onConnect($client_id)
    {
//        $db1 = Db::instance('db1');
//        $insert_id = $db1->insert('test')->cols(array('name' => "FG_onConnect=" . $client_id))->query();
//
//        Gateway::sendToClient($client_id, json_encode(array(
//            'type' => 'init',
//            'client_id' => $client_id
//        )));

//        Gateway::sendToClient($client_id, "\$GN");
//        $db1 = Db::instance('db1');
//        $device = $db1->select('*')
//            ->from('fa_feige_device')
//            ->where('client_id= :client_id')
//            ->orderByASC(array('update_time'))
//            ->limit(1)
//            ->bindValues(array('client_id' => '7f0000010f500000000e'))
//            ->row();
//
//        if ($device) {
//            $device_id = $device['id'];
//        }

    }

    public static function onMessage($client_id, $message)
    {
        try {
    //        Gateway::sendToClient($client_id, "".$client_id);
            //如果用web API给client发指令，这里可以不处理
            $db1 = Db::instance('db1');
            $message = str_replace(array("\r\n", "\r", "\n"), "", $message);
            $insert_id = $db1->insert('test')->cols(array('name' => "client_id=" . $client_id . " --- FG_onMessage2=" . $message))->query();

            if (strncmp($message, ">MREG", 6) == 1) {
                //>MREG,PD-077,85008353819*24
                $xor = substr($message, strlen($message) - 2);
                $value = substr($message, 1, strlen($message) - 4);
                $s1 = Events::getXOR($value);
    //            if ($xor == $s1) {
    //                Gateway::sendToClient($client_id, '@SREG,eggi.megowx.com,8901*61');
                return;
    //            }
            } else if (strncmp($message, ">", 2) == 1) {
    //            >85008353818,00,022140,A,N2444.9801,E12144.4167,0.00,0.00,310119,1014,6*77
                $value = $message;
                $v = explode("*", $message);
                if (count($v) > 1) {
                    $xor = $v[1];
                    $value = $v[0];
    //                $s1 = Events::getXOR($value);
    //                if ($xor == $s1)   //校验码判断
                } else {
                    //只有前一半
                    $record = explode(",", $value);
                    $mobile = '';
                    if (!empty($record) && is_array($record)) {
                        $mobile = $record[0];
                        $mobile = str_replace(">", '', $mobile);
                    }

                    if (empty($mobile)) {
                        return;
                    }

                    $device_id = $db1->select('id')
                        ->from('fa_feige_device')
                        ->where('name= :name')
                        ->bindValues(array('name' => $mobile))
                        ->single();

                    $data = array(
                        'client_id' => $client_id,
                        'name' => $mobile,
                        'content' => $message,
                        'isonline' => 1,
                        'update_time' => date('Y-m-d H:i:s', time())
                    );

                    if (empty($device_id)) {
                        $device_id = $db1->insert('fa_feige_device')->cols($data)->query();
                    } else {
                        $db1->update('fa_feige_device')->cols($data)->where("id=" . $device_id)->query();
                    }

                    return;
                }

                Events::saverecord($client_id, $value);
            } else if (strpos($message,'*') !== false) {
                //包含 *  --- 尾段

                $record = explode(",", $message);
                $mobile = '';
                if (!empty($record) && is_array($record)) {
                    $mobile = $record[0];
                    $mobile = str_replace(">", '', $mobile);
                }

                if (empty($mobile)) {
                    return;
                }

                $message = str_replace($mobile.",", '', $message);

                $device = $db1->select('*')
                    ->from('fa_feige_device')
                    ->where('name= :name')
                    ->bindValues(array('name' => $mobile))
                    ->limit(1)
                    ->row();

    //            $device = $db1->select('*')
    //                ->from('fa_feige_device')
    //                ->where('client_id= :client_id')
    //                ->orderByDESC(array('update_time'))
    //                ->limit(1)
    //                ->bindValues(array('client_id' => $client_id))
    //                ->row();

                if ($device) {
                    $device_id = $device['id'];
                    $content = $device['content'];
                    $value = $content.$message;

                    if (strpos($value,'>') !== false) {
                        $v = explode("*", $value);
                        if (count($v) > 1) {
                            $xor = $v[1];
                            $value = $v[0];
                            Events::saverecord($client_id, $value);
                        }
                    }
                }
            } else {
                // * 和 > 都没有 -- 中间段

                $record = explode(",", $message);
                $mobile = '';
                if (!empty($record) && is_array($record)) {
                    $mobile = $record[0];
                    $mobile = str_replace(">", '', $mobile);
                }

                if (empty($mobile)) {
                    return;
                }

                $message = str_replace($mobile.",", '', $message);

                $device = $db1->select('*')
                    ->from('fa_feige_device')
                    ->where('name= :name')
                    ->bindValues(array('name' => $mobile))
                    ->limit(1)
                    ->row();

                if ($device) {
                    $device_id = $device['id'];
                    $content = $device['content'];
                    $content = $content.$message;
                    if (!empty($device_id)) {
                        $data = array(
                            'content' => $content,
                            'isonline' => 1
                        );
                        $db1->update('fa_feige_device')->cols($data)->where("id=" . $device_id)->query();
                    }
                }
            }
        } catch (\Exception $e) {
            exit(250);
        }  catch (\Error $e) {
            exit(250);
        }

    }

    public static function onClose($client_id)
    {
        $db1 = Db::instance('db1');
        $device_id = $db1->select('id')
            ->from('fa_feige_device')
            ->where('client_id= :client_id')
            ->orderByDESC(array('update_time'))
            ->limit(1)
            ->bindValues(array('client_id' => $client_id))
            ->single();

        if (!empty($device_id)) {
            $data = array(
                'isonline' => 0,
                'update_time' => date('Y-m-d H:i:s', time())
            );
            $db1->update('fa_feige_device')->cols($data)->where("id=" . $device_id)->query();
        }
    }

    public static function getXOR($value)
    {
        if (empty($value)) {
            return "";
        }
        $aa = "";
        for ($i = 0; $i < strlen($value); $i++) {
            $bb = substr($value, $i, 1);
            if ($i == 0) {
                $aa = $bb;
            } else {
                $aa = $aa ^ $bb;
            }
        }

        $s1 = strtoupper(bin2hex($aa));
        return $s1;
    }

    public static function saverecord($client_id, $value)
    {
        if (empty($client_id) || empty($value)) {
            return;
        }
        try {
            $db1 = Db::instance('db1');
            $record = explode(",", $value);
            if (!empty($record) && is_array($record)) {

                $mobile = $record[0];
                $mobile = str_replace(">", '', $mobile);
                $index = intval($record[1]);
                if ($index == 99) {
                    //批量上传
                    Events::saverecord3($client_id, $value);
                    return;
                }

                if (count($record) < 11) {
                    //心跳包 + 上传电池电量
                    Events::saverecord2($client_id, $value);
                    return;
                }

    //            06819296100,10,015702,A,N2236.1876,E11350.9521,0.00,1202590848.00,030000,1014,9*7D
    //            06819296102,99,00000024,083224,V,N2236.1818,E11350.9384,
                $state = $record[3];
                $lng = $record[5];
                $lat = $record[4];
                $vel = $record[6];
                $dir = $record[7];
                $zhixun = $record[9];
                $powerlevel = intval($record[10]);
                if ($powerlevel > 9) {
                    $powerlevel = 9;
                }

                $device_id = $db1->select('id')
                    ->from('fa_feige_device')
                    ->where('name= :name')
                    ->bindValues(array('name' => $mobile))
                    ->single();

                $data = array(
                    'client_id' => $client_id,
                    'name' => $mobile,
                    'isonline' => 1,
                    'update_time' => date('Y-m-d H:i:s', time())
                );

                if ($state == "A") {
                    $data['lng'] = $lng;
                    $data['lat'] = $lat;
                }

                if (empty($device_id)) {
                    $data['name'] = $mobile;
                    $device_id = $db1->insert('fa_feige_device')->cols($data)->query();
                } else {
                    $db1->update('fa_feige_device')->cols($data)->where("id=" . $device_id)->query();
                }

                $db1->insert('fa_feige_records')->cols(
                    array(
                        'device_id' => $device_id,
                        'mobile' => $mobile,
                        'index' => $index,
                        'state' => $state,
                        'lng' => $lng,
                        'lat' => $lat,
                        'vel' => $vel,
                        'dir' => $dir,
                        'zhixun' => $zhixun,
                        'isxt' => 0,
                        'powerlevel' => $powerlevel
                    )
                )->query();
            }
        } catch (\Exception $e) {
            exit(250);
        }  catch (\Error $e) {
            exit(250);
        }
    }

    public static function saverecord2($client_id, $value)
    {
        //心跳包或电量
        if (empty($client_id) || empty($value)) {
            return;
        }
        try {
            $db1 = Db::instance('db1');
            $record = explode(",", $value);
            if (!empty($record) && is_array($record)) {

                if (count($record) < 7) {
                    return;
                }
                $mobile = $record[0];
                $mobile = str_replace(">", '', $mobile);
                $index = intval($record[1]);
                $state = $record[3];
                $lng = $record[5];
                $lat = $record[4];
                $powerlevel = intval($record[6]);
                if ($powerlevel > 9) {
                    $powerlevel = 9;
                }

                $device_id = $db1->select('id')
                    ->from('fa_feige_device')
                    ->where('name= :name')
                    ->bindValues(array('name' => $mobile))
                    ->single();

                $data = array(
                    'client_id' => $client_id,
                    'isonline' => 1,
                    'update_time' => date('Y-m-d H:i:s', time())
                );

                if ($state == "A") {
                    $data['lng'] = $lng;
                    $data['lat'] = $lat;
                }

                if (empty($device_id)) {
                    $data['name'] = $mobile;
                    $device_id = $db1->insert('fa_feige_device')->cols($data)->query();
                } else {
                    $db1->update('fa_feige_device')->cols($data)->where("id=" . $device_id)->query();
                }

                $data1 = array(
                    'device_id' => $device_id,
                    'index' => $index,
                    'mobile' => $mobile,
                    'lng' => $lng,
                    'lat' => $lat,
                    'isxt' => 1,
                    'state' => $state,
                    'powerlevel' => $powerlevel
                );
                $db1->insert('fa_feige_records')->cols($data1)->query();
            }
        } catch (\Exception $e) {
            exit(250);
        }  catch (\Error $e) {
            exit(250);
        }
    }


    //批量上传
    public static function saverecord3($client_id, $value)
    {
        if (empty($client_id) || empty($value)) {
            return;
        }

//        $value = ">01231231006,99,00000321,102929,V,142332-N2236.3108-142432-N2236.3732-E11350.8394,140905-N2236.4406-E11350.7515,9*5B";
        try {
            $db1 = Db::instance('db1');
            $record = explode(",", $value);
            if (!empty($record) && is_array($record)) {

//            06819296102,99,00000024,083224,V,N2236.1818,E11350.9384,9 *49
//            >06819296188,99,00000207,132956,V,134106,000000.0000,00000.0000,
// >06666666661,99,00000011,034036,V,034036-N2236.1789-E11350.9198,034106-N2236.1859-E11350.9328,9*1B  -- ok
// >01231231006,99,00000321,102929,V,142332-N2236.3108-142432-N2236.3732-E11350.8394,140905-N2236.4406-E11350.7515,9*5B   -- err
                $mobile = $record[0];
                $mobile = str_replace(">", '', $mobile);
                $index = intval($record[1]);
                if ($index != 99) {
                    return;
                }
                $num = intval($record[2]);
                $num = (count($record) - 6);//应该一样

                $state = $record[4];
                $powerlevel = intval($record[$num - 1]);

                $device_id = $db1->select('id')
                    ->from('fa_feige_device')
                    ->where('name= :name')
                    ->bindValues(array('name' => $mobile))
                    ->single();

                $date = date('Y-m-d ', time());
                for ($i = 0; $i < $num; $i++) {

                    $datas = explode("-", $record[$i + 5]);

                    if (count($datas) != 3) {
                        continue;
                    }
                    $date1 = '';
                    $time = $datas[0];
                    $lat = $datas[1];
                    $lng = $datas[2];

                    //132956
                    if (strlen($time) == 6) {
                        $time0 = substr($time, 0, 2);
                        $time1 = substr($time, 2, 2);
                        $time2 = substr($time, 4, 2);
//                    11:26:28
                        $time0 = intval($time0) + 8;
                        if ($time0 > 24) {
                            $time0 = $time0 - 24;
                        }
                        $date1 = $date.$time0.":".$time1.":".$time2;
                    }

                    $data = array(
                        'client_id' => $client_id,
                        'name' => $mobile,
                        'isonline' => 1,
                        'update_time' => date('Y-m-d H:i:s', time())
                    );

                    if ($state == "A") {
                        $data['lng'] = $lng;
                        $data['lat'] = $lat;
                    }

                    if (empty($device_id)) {
                        $data['name'] = $mobile;
                        $device_id = $db1->insert('fa_feige_device')->cols($data)->query();
                    } else {
                        $db1->update('fa_feige_device')->cols($data)->where("id=" . $device_id)->query();
                    }

                    $data1 = array(
                        'device_id' => $device_id,
                        'mobile' => $mobile,
                        'index' => $i,
                        'state' => $state,
                        'lng' => $lng,
                        'lat' => $lat,
                        'powerlevel' => $powerlevel,
                        'record_time' => $date1
                    );

                    $db1->insert('fa_feige_records')->cols($data1)->query();
                }
            }
        } catch (\Exception $e) {
            exit(250);
        }  catch (\Error $e) {
            exit(250);
        }

    }

}
